<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Common\Tree;
class CategoryController extends CommonController {
	
	public function index(){
		$sql = "select * from category_test";
		$category = M()->query($sql);
		$treeObj = new Tree();
		$reformResult = $treeObj->categoryReform($category,0);
		$this->assign('category',$reformResult);
		$this->display();
	}

	//异步删除
	public function categorydelete(){
		if(IS_POST && IS_AJAX){
			$cateid = $_POST['cateid'];
			//取到类别的id之后先查询是否有包含子类
			$sql = "select * from category_test where fid = {$cateid}";
			//如果含有数据就提示说有子类
			if(M()->query($sql)){
				$returnMsg = array(
					'error' => '1',
					'msg'   => '包含子类,请先删除该类的子类再做操作',
				);
			}else{
				//如果不包含子类就做删除 
				$sql = "delete from category_test where id = {$cateid}";
				if(M()->execute($sql)){
					$returnMsg = array(
						'error' => '0',
						'msg'   => '删除成功',
					);
				}
				
			}
			
		}else{
			$returnMsg = array(
					'error' => '1',
					'msg'   => '非法操作。',
				);
		}
		$this->ajaxReturn($returnMsg);
	}

	// 添加
	public function categoryadd(){
		$data['fid'] = $_POST['fid'];
		$data['cname'] = $_POST['cname'];
		if(M('category_test')->add($data)){
			$this->success('添加成功',U('admin/category/index'));
		}else{
			$this->error('添加失败');
		}
	}

	//修改
	public function categoryedit(){
		if($_GET['id']){
			$sql = "select * from category_test";
			$category = M()->query($sql);
			$treeObj = new Tree();
			$reformResult = $treeObj->categoryReform($category,0);
			$oldid = M('category_test')->where("id = {$_GET['id']}")->getField('id');	//老的id
			$oldcname = M('category_test')->where("id = {$_GET['id']}")->getField('cname');	//老的cname
			$oldfid = M('category_test')->where("id = {$_GET['id']}")->getField('fid');  //老的fid
			$this->assign('oldcname',$oldcname);
			$this->assign('oldid',$oldid);
			$this->assign('oldfid',$oldfid);
			$this->assign('category',$reformResult);
			$this->display();
		}elseif($_POST){
			$dataRes['id'] = $_POST['id'];
			$dataRes['fid'] = $_POST['fid'];
			$dataRes['cname'] = $_POST['cname'];
			if(M('category_test')->save($dataRes)){
				$this->success('修改成功',U('admin/category/index'));
			}else{
				$this->error('修改失败',U('admin/category/index'));
			}
		}else{
			$this->error('非法访问',U('admin/category/index'));
		}
		
	}
}